<template>
  <div class="dashboard-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-card class="welcome-card" shadow="never">
        <div class="welcome-content">
          <div class="welcome-text">
            <h2>欢迎回来，{{ userInfo.nickName || userInfo.userName || '用户' }}！</h2>
            <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
          </div>
          <div class="welcome-icon">
            <i class="el-icon-sunny"></i>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card" shadow="hover" @click.native="handleOrderClick">
            <div class="stats-content">
              <div class="stats-icon orders">
                <i class="el-icon-s-order"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ orderStats.total || 0 }}</div>
                <div class="stats-label">今日订单数</div>
              </div>
            </div>
            <div class="stats-footer">
              <span class="stats-trend up" v-if="orderStats.trend > 0">
                <i class="el-icon-top"></i> +{{ orderStats.trend }}%
              </span>
              <span class="stats-trend down" v-else-if="orderStats.trend < 0">
                <i class="el-icon-bottom"></i> {{ orderStats.trend }}%
              </span>
              <span class="stats-trend" v-else>
                <i class="el-icon-minus"></i> 0%
              </span>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card" shadow="hover" @click.native="handleProductClick">
            <div class="stats-content">
              <div class="stats-icon products">
                <i class="el-icon-goods"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ productStats.total || 0 }}</div>
                <div class="stats-label">商品总数</div>
              </div>
            </div>
            <div class="stats-footer">
              <span class="stats-trend up" v-if="productStats.trend > 0">
                <i class="el-icon-top"></i> +{{ productStats.trend }}%
              </span>
              <span class="stats-trend down" v-else-if="productStats.trend < 0">
                <i class="el-icon-bottom"></i> {{ productStats.trend }}%
              </span>
              <span class="stats-trend" v-else>
                <i class="el-icon-minus"></i> 0%
              </span>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card" shadow="hover" @click.native="handleUserClick">
            <div class="stats-content">
              <div class="stats-icon users">
                <i class="el-icon-user"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ userStats.total || 0 }}</div>
                <div class="stats-label">用户总数</div>
              </div>
            </div>
            <div class="stats-footer">
              <span class="stats-trend up" v-if="userStats.trend > 0">
                <i class="el-icon-top"></i> +{{ userStats.trend }}%
              </span>
              <span class="stats-trend down" v-else-if="userStats.trend < 0">
                <i class="el-icon-bottom"></i> {{ userStats.trend }}%
              </span>
              <span class="stats-trend" v-else>
                <i class="el-icon-minus"></i> 0%
              </span>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card" shadow="hover" @click.native="handleRefundClick">
            <div class="stats-content">
              <div class="stats-icon refunds">
                <i class="el-icon-refresh-left"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ refundStats.total || 0 }}</div>
                <div class="stats-label">今日退款订单数</div>
              </div>
            </div>
            <div class="stats-footer">
              <span class="stats-trend up" v-if="refundStats.trend > 0">
                <i class="el-icon-top"></i> +{{ refundStats.trend }}%
              </span>
              <span class="stats-trend down" v-else-if="refundStats.trend < 0">
                <i class="el-icon-bottom"></i> {{ refundStats.trend }}%
              </span>
              <span class="stats-trend" v-else>
                <i class="el-icon-minus"></i> 0%
              </span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 销售趋势图 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span class="chart-title">销售趋势</span>
              <div class="chart-controls">
                <el-button-group>
                  <el-button size="mini" :type="salesTrendPeriod === '7d' ? 'primary' : ''" @click="changeSalesTrendPeriod('7d')">7天</el-button>
                  <el-button size="mini" :type="salesTrendPeriod === '30d' ? 'primary' : ''" @click="changeSalesTrendPeriod('30d')">30天</el-button>
                  <el-button size="mini" :type="salesTrendPeriod === '90d' ? 'primary' : ''" @click="changeSalesTrendPeriod('90d')">90天</el-button>
                </el-button-group>
              </div>
            </div>
            <div id="salesTrendChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 商品分类分布 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span class="chart-title">商品分类分布</span>
            </div>
            <div id="categoryChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 用户活跃度 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span class="chart-title">用户活跃度</span>
            </div>
            <div id="userActivityChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 热销商品排行 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span class="chart-title">热销商品排行</span>
            </div>
            <div class="hot-products-list">
              <div v-for="(product, index) in hotProductsData" :key="index" class="hot-product-item">
                <div class="product-rank">{{ index + 1 }}</div>
                <div class="product-info">
                  <div class="product-name">{{ product.name }}</div>
                  <div class="product-sales">销量: {{ product.sales }}</div>
                </div>
                <div class="product-amount">¥{{ formatNumber(product.amount) }}</div>
              </div>
              <div v-if="!hotProductsData.length" class="no-data">
                <i class="el-icon-goods"></i>
                <p>暂无商品数据</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近动态区域 -->
    <div class="recent-section">
      <el-row :gutter="20">
        <!-- 最近订单 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="recent-card" shadow="hover">
            <div slot="header" class="recent-header">
              <span class="recent-title">最近订单</span>
            </div>
            <div class="recent-list">
              <div v-for="(order, index) in recentOrders" :key="index" class="recent-item">
                <div class="item-icon">
                  <i class="el-icon-s-order"></i>
                </div>
                <div class="item-content">
                  <div class="item-title">订单号: {{ order.orderNo }}</div>
                  <div class="item-desc">金额: ¥{{ formatNumber(order.totalAmount) }}</div>
                </div>
                <div class="item-time">{{ formatTime(order.createTime) }}</div>
              </div>
              <div v-if="!recentOrders.length" class="no-data">
                <i class="el-icon-document"></i>
                <p>暂无订单</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 系统信息 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card class="recent-card" shadow="hover">
            <div slot="header" class="recent-header">
              <span class="recent-title">系统信息</span>
            </div>
            <div class="system-info">
              <div class="info-item">
                <span class="info-label">系统版本:</span>
                <span class="info-value">迭代猫在线商城Iterativecat.cn V1.0.0</span>
              </div>
              <div class="info-item">
                <span class="info-label">服务状态:</span>
                <span class="info-value">正常运行</span>
              </div>
              <div class="info-item">
                <span class="info-label">当前组织:</span>
                <span class="info-value">{{ userInfo.deptName || '暂无组织' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">用户角色:</span>
                <span class="info-value">{{ userInfo.roles && userInfo.roles.length > 0 ? userInfo.roles[0] : '普通用户' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getStatsData, getOrderStats, getUserStats, getProductStats, getRevenueStats, getSalesTrend, getCategoryDistribution, getUserActivity, getHotProducts, getRecentOrders, getSystemInfo } from '@/api/dashboard/stats'
import { getToken } from '@/utils/auth'
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      // 用户信息
      userInfo: {},
      // 当前日期
      currentDate: '',
      // 统计数据
      orderStats: {
        total: 0,
        trend: 0
      },
      productStats: {
        total: 0,
        trend: 0
      },
      userStats: {
        total: 0,
        trend: 0
      },
      refundStats: {
        total: 0,
        trend: 0
      },
      // 图表数据
      salesTrendPeriod: '30d',
      salesTrendData: [],
      categoryData: [],
      userActivityData: [],
      hotProducts: [],
      hotProductsData: [],
      recentOrders: [],
      // 系统信息
      systemInfo: {
        uptime: ''
      },
      // 图表实例
      salesTrendChart: null,
      categoryChart: null,
      userActivityChart: null
    }
  },
  async created() {
    await this.initData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })

    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)

    // 销毁图表实例
    if (this.salesTrendChart) {
      this.salesTrendChart.dispose()
    }
    if (this.categoryChart) {
      this.categoryChart.dispose()
    }
    if (this.userActivityChart) {
      this.userActivityChart.dispose()
    }
  },
  methods: {
    // 初始化数据
    async initData() {
      console.log('🚀 开始初始化数据...')

      // 获取用户信息 - 从store的分散字段中构建用户信息对象
      const userState = this.$store.state.user
      this.userInfo = {
        userId: userState.id,
        userName: userState.name,
        nickName: userState.nickName,
        avatar: userState.avatar,
        roles: userState.roles,
        permissions: userState.permissions,
        deptId: userState.deptId,
        deptName: userState.deptName
      }
      this.currentDate = this.formatDate(new Date())

      console.log('👤 用户信息:', this.userInfo)
      console.log('📅 当前日期:', this.currentDate)
      console.log('🏪 Store完整状态:', this.$store.state)

      // 检查用户是否已登录
      if (!this.userInfo.userName) {
        console.warn('⚠️ 用户信息为空，可能未登录')
        // 尝试重新获取用户信息
        try {
          await this.$store.dispatch('GetInfo')
          const newUserState = this.$store.state.user
          this.userInfo = {
            userId: newUserState.id,
            userName: newUserState.name,
            nickName: newUserState.nickName,
            avatar: newUserState.avatar,
            roles: newUserState.roles,
            permissions: newUserState.permissions,
            deptId: newUserState.deptId,
            deptName: newUserState.deptName
          }
          console.log('🔄 重新获取用户信息:', this.userInfo)
        } catch (error) {
          console.error('❌ 获取用户信息失败:', error)
        }
      }

      console.log('📊 开始并行加载所有数据...')
      // 并行加载所有数据
      await Promise.all([
        this.loadStatsData(),
        this.loadChartsData(),
        this.loadRecentData()
      ])

      console.log('✅ 所有数据加载完成')

      // 数据加载完成后，如果已经mounted，则初始化图表
      if (this._isMounted) {
        console.log('🎨 组件已挂载，初始化图表...')
        this.$nextTick(() => {
          this.initCharts()
        })
      } else {
        console.log('⏳ 组件未挂载，等待mounted后初始化图表')
      }

      console.log('🎉 数据初始化完成')
    },

    // 加载统计数据
    async loadStatsData() {
      try {
        console.log('📊 开始加载统计数据...')

        // 使用统一接口获取所有统计数据
        console.log('📡 发起统计数据API请求...')
        const statsRes = await getStatsData().catch(err => {
          console.error('❌ 统计数据API失败:', err)
          return { data: null, error: err }
        })

        console.log('📊 统计数据API响应结果:', statsRes)

        // 处理统计数据
        if (statsRes.data) {
          const stats = statsRes.data

          // 处理订单统计数据
          if (stats.orders) {
            this.orderStats = {
              total: stats.orders.total || 0,
              trend: stats.orders.trend || 0
            }
            console.log('✅ 订单统计数据处理完成:', this.orderStats)
          }

          // 处理商品统计数据
          if (stats.products) {
            this.productStats = {
              total: stats.products.total || 0,
              trend: stats.products.trend || 0
            }
            console.log('✅ 商品统计数据处理完成:', this.productStats)
          }

          // 处理用户统计数据
          if (stats.users) {
            this.userStats = {
              total: stats.users.total || 0,
              trend: stats.users.trend || 0
            }
            console.log('✅ 用户统计数据处理完成:', this.userStats)
          }

          // 处理退款统计数据
          if (stats.refunds) {
            this.refundStats = {
              total: stats.refunds.total || 0,
              trend: stats.refunds.trend || 0
            }
            console.log('✅ 退款统计数据处理完成:', this.refundStats)
          }
        } else {
          console.log('⚠️ 统计数据为空，使用默认值')
          this.orderStats = { total: 0, trend: 0 }
          this.productStats = { total: 0, trend: 0 }
          this.userStats = { total: 0, trend: 0 }
          this.refundStats = { total: 0, trend: 0 }
        }

        console.log('🎉 统计数据加载完成')
      } catch (error) {
        console.error('💥 加载统计数据失败:', error)
        console.error('错误详情:', error.message, error.stack)
        this.$message.error('加载统计数据失败: ' + error.message)

        // 使用默认值作为降级方案
        console.log('🔄 使用默认值作为降级方案')
        this.orderStats = { total: 0, trend: 0 }
        this.productStats = { total: 0, trend: 0 }
        this.userStats = { total: 0, trend: 0 }
        this.refundStats = { total: 0, trend: 0 }
        console.log('✅ 降级方案数据设置完成')
      }
    },

    // 加载图表数据
    async loadChartsData() {
      try {
        // 获取当前用户的组织ID，确保为数字类型
        const orgId = this.$store.getters.orgId || this.$store.getters.user && this.$store.getters.user.deptId
        const params = orgId ? { orgId: parseInt(orgId) } : {}

        console.log('📈 开始加载图表数据, orgId:', orgId, 'params:', params)

        // 获取图表数据，考虑组织ID过滤
        console.log('📡 发起图表API请求...')
        const [salesRes, categoryRes, activityRes, hotRes] = await Promise.all([
          getSalesTrend({ ...params, period: this.salesTrendPeriod }).catch(err => {
            console.error('❌ 销售趋势API失败:', err)
            return { data: null, error: err }
          }),
          getCategoryDistribution(params).catch(err => {
            console.error('❌ 分类分布API失败:', err)
            return { data: null, error: err }
          }),
          getUserActivity({ ...params, period: '30d' }).catch(err => {
            console.error('❌ 用户活跃度API失败:', err)
            return { data: null, error: err }
          }),
          getHotProducts({ ...params, limit: parseInt(10) }).catch(err => {
            console.error('❌ 热销商品API失败:', err)
            return { data: null, error: err }
          })
        ])

        console.log('📊 图表API响应结果:')
        console.log('  销售趋势:', salesRes)
        console.log('  分类分布:', categoryRes)
        console.log('  用户活跃度:', activityRes)
        console.log('  热销商品:', hotRes)

        // 处理销售趋势数据
        if (salesRes.data && Array.isArray(salesRes.data)) {
          this.salesTrendData = salesRes.data
          console.log('✅ 销售趋势数据处理完成:', this.salesTrendData)
        } else {
          this.salesTrendData = this.generateSalesTrendData()
          console.log('⚠️ 销售趋势数据为空，使用模拟数据:', this.salesTrendData)
        }

        // 处理分类数据
        if (categoryRes.data && Array.isArray(categoryRes.data)) {
          this.categoryData = categoryRes.data
          console.log('✅ 分类数据处理完成:', this.categoryData)
        } else {
          this.categoryData = this.generateCategoryData()
          console.log('⚠️ 分类数据为空，使用模拟数据:', this.categoryData)
        }

        // 处理用户活跃度数据
        if (activityRes.data && Array.isArray(activityRes.data)) {
          this.userActivityData = activityRes.data
          console.log('✅ 用户活跃度数据处理完成:', this.userActivityData)
        } else {
          this.userActivityData = this.generateUserActivityData()
          console.log('⚠️ 用户活跃度数据为空，使用模拟数据:', this.userActivityData)
        }

        // 处理热销商品数据
        if (hotRes.data && Array.isArray(hotRes.data) && hotRes.data.length > 0) {
          this.hotProductsData = hotRes.data
          console.log('✅ 热销商品数据处理完成:', this.hotProductsData)
        } else {
          this.hotProductsData = []
          console.log('⚠️ 热销商品数据为空，显示空状态')
        }

        // 更新图表
        console.log('🎨 开始更新图表...')
        this.$nextTick(() => {
          this.updateSalesTrendChart()
          this.updateCategoryChart()
          this.updateUserActivityChart()
          console.log('✅ 图表更新完成')
        })
      } catch (error) {
        console.error('💥 加载图表数据失败:', error)
        console.error('错误详情:', error.message, error.stack)
        this.$message.error('加载图表数据失败: ' + error.message)

        // 使用模拟数据作为降级方案
        console.log('🔄 使用模拟数据作为降级方案')
        this.salesTrendData = this.generateSalesTrendData()
        this.categoryData = this.generateCategoryData()
        this.userActivityData = this.generateUserActivityData()
        this.hotProductsData = this.generateHotProductsData()

        // 更新图表
        this.$nextTick(() => {
          this.updateSalesTrendChart()
          this.updateCategoryChart()
          this.updateUserActivityChart()
          console.log('✅ 降级方案图表更新完成')
        })
      }
    },

    // 加载最近数据
    async loadRecentData() {
      try {
        // 获取当前用户的组织ID，确保为数字类型
        const orgId = this.$store.getters.orgId || this.$store.getters.user && this.$store.getters.user.deptId
        const params = orgId ? { orgId: parseInt(orgId), limit: parseInt(5) } : { limit: parseInt(5) }

        console.log('📋 开始加载最近数据, orgId:', orgId, 'params:', params)

        // 获取最近订单，考虑组织ID过滤
        console.log('📡 发起最近数据API请求...')
        const [recentRes, systemRes] = await Promise.all([
          getRecentOrders(params).catch(err => {
            console.error('❌ 最近订单API失败:', err)
            return { data: null, error: err }
          }),
          getSystemInfo().catch(err => {
            console.error('❌ 系统信息API失败:', err)
            return { data: null, error: err }
          })
        ])

        console.log('📊 最近数据API响应结果:')
        console.log('  最近订单:', recentRes)
        console.log('  系统信息:', systemRes)

        // 处理最近订单数据
        if (recentRes.data && Array.isArray(recentRes.data)) {
          this.recentOrders = recentRes.data.map(order => ({
            orderNo: order.orderNo || order.id,
            totalAmount: parseFloat(order.totalAmount || 0),
            createTime: order.createTime || new Date().toISOString()
          }))
          console.log('✅ 最近订单数据处理完成:', this.recentOrders)
        } else {
          this.recentOrders = this.generateRecentOrdersData()
          console.log('⚠️ 最近订单数据为空，使用模拟数据:', this.recentOrders)
        }

        // 处理系统信息数据
        if (systemRes.data && systemRes.data.uptime) {
          this.systemInfo = systemRes.data
          console.log('✅ 系统信息数据处理完成:', this.systemInfo)
        } else {
          this.systemInfo = { uptime: '7天 12小时 30分钟' }
          console.log('⚠️ 系统信息数据为空，使用默认值:', this.systemInfo)
        }

        console.log('🎉 最近数据加载完成')
      } catch (error) {
        console.error('💥 加载最近数据失败:', error)
        console.error('错误详情:', error.message, error.stack)
        this.$message.error('加载最近数据失败: ' + error.message)

        // 使用模拟数据作为降级方案
        console.log('🔄 使用模拟数据作为降级方案')
        this.recentOrders = this.generateRecentOrdersData()
        this.systemInfo.uptime = '7天 12小时 30分钟'
        console.log('✅ 降级方案数据设置完成')
      }
    },

    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.initSalesTrendChart()
        this.initCategoryChart()
        this.initUserActivityChart()
      })
    },

    // 初始化销售趋势图
    initSalesTrendChart() {
      const chartDom = document.getElementById('salesTrendChart')
      if (!chartDom) {
        console.warn('销售趋势图表DOM元素未找到')
        return
      }

      this.salesTrendChart = echarts.init(chartDom)
      this.updateSalesTrendChart()
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.salesTrendChart) {
        this.salesTrendChart.resize()
      }
      if (this.categoryChart) {
        this.categoryChart.resize()
      }
      if (this.userActivityChart) {
        this.userActivityChart.resize()
      }
    },

    // 更新销售趋势图
    updateSalesTrendChart() {
      if (!this.salesTrendChart) return

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.salesTrendData.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.salesTrendData.map(item => item.value),
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }

      this.salesTrendChart.setOption(option)
    },

    // 初始化分类图表
    initCategoryChart() {
      const chartDom = document.getElementById('categoryChart')
      if (!chartDom) {
        console.warn('分类图表DOM元素未找到')
        return
      }

      this.categoryChart = echarts.init(chartDom)
      this.updateCategoryChart()
    },

    // 更新分类图表
    updateCategoryChart() {
      if (!this.categoryChart) return

      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: this.categoryData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.categoryChart.setOption(option)
    },

    // 初始化用户活跃度图表
    initUserActivityChart() {
      const chartDom = document.getElementById('userActivityChart')
      if (!chartDom) {
        console.warn('用户活跃度图表DOM元素未找到')
        return
      }

      this.userActivityChart = echarts.init(chartDom)
      this.updateUserActivityChart()
    },

    // 更新用户活跃度图表
    updateUserActivityChart() {
      if (!this.userActivityChart) return

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const data = params[0]
            return `${data.name}<br/>浏览足迹数量: ${data.value}`
          }
        },
        xAxis: {
          type: 'category',
          data: this.userActivityData.map(item => item.date)
        },
        yAxis: {
          type: 'value',
          name: '浏览足迹数量'
        },
        series: [{
          name: '浏览足迹数量',
          data: this.userActivityData.map(item => item.value),
          type: 'bar',
          itemStyle: {
            color: '#67C23A'
          }
        }]
      }

      this.userActivityChart.setOption(option)
    },

    // 处理销售趋势数据
    processSalesTrendData(orders) {
      const data = []
      const days = this.salesTrendPeriod === '7d' ? 7 : this.salesTrendPeriod === '30d' ? 30 : 90

      // 按日期分组统计订单金额
      const dateMap = {}
      orders.forEach(order => {
        const date = this.formatDate(new Date(order.createTime), 'MM-DD')
        if (!dateMap[date]) {
          dateMap[date] = 0
        }
        dateMap[date] += parseFloat(order.totalAmount || 0)
      })

      // 生成最近N天的数据
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        const dateStr = this.formatDate(date, 'MM-DD')
        data.push({
          date: dateStr,
          value: dateMap[dateStr] || 0
        })
      }

      return data
    },

    // 处理分类数据
    processCategoryData(categories) {
      if (!categories || categories.length === 0) {
        return [{ value: 0, name: '暂无数据' }]
      }
      return categories.slice(0, 5).map(category => ({
        value: 0, // 默认值为0，实际应该从统计数据中获取
        name: category.categoryName || category.name || '未知分类'
      }))
    },

    // 处理用户活跃度数据
    processUserActivityData(users) {
      const data = []
      for (let i = 6; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        data.push({
          date: this.formatDate(date, 'MM-DD'),
          value: 0 // 默认值为0，实际应该从用户活跃度统计中获取
        })
      }
      return data
    },

    // 处理热销商品数据
    processHotProductsData(products) {
      if (!products || products.length === 0) {
        return [{ name: '暂无数据', sales: 0, amount: 0 }]
      }
      return products.slice(0, 5).map(product => ({
        name: product.productName || product.name || '未知商品',
        sales: 0, // 默认值为0，实际应该从销售统计中获取
        amount: parseFloat(product.price || product.salePrice || 0)
      }))
    },

    // 切换销售趋势周期
    async changeSalesTrendPeriod(period) {
      this.salesTrendPeriod = period

      try {
        // 获取当前用户的组织ID，确保为数字类型
        const orgId = this.$store.getters.orgId || this.$store.getters.user && this.$store.getters.user.deptId
        const params = orgId ? { orgId: parseInt(orgId), period } : { period }

        // 重新获取销售趋势数据
        const salesRes = await getSalesTrend(params)
        this.salesTrendData = salesRes.data || this.generateSalesTrendData()
      } catch (error) {
        console.error('获取销售趋势数据失败:', error)
        // 使用模拟数据作为降级方案
        this.salesTrendData = this.generateSalesTrendData()
      }

      this.updateSalesTrendChart()
    },

    // 生成模拟销售趋势数据
    generateSalesTrendData() {
      const data = []
      const days = this.salesTrendPeriod === '7d' ? 7 : this.salesTrendPeriod === '30d' ? 30 : 90

      for (let i = days - 1; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        data.push({
          date: this.formatDate(date, 'MM-DD'),
          value: 0 // 默认值为0
        })
      }

      return data
    },

    // 生成模拟分类数据
    generateCategoryData() {
      return [
        { value: 0, name: '暂无数据' }
      ]
    },

    // 生成模拟用户活跃度数据
    generateUserActivityData() {
      const data = []
      for (let i = 6; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        data.push({
          date: this.formatDate(date, 'MM-DD'),
          value: 0 // 默认值为0
        })
      }
      return data
    },

    // 生成模拟热销商品数据
    generateHotProductsData() {
      return [
        { name: '暂无数据', sales: 0, amount: 0 }
      ]
    },

    // 生成模拟最近订单数据
    generateRecentOrdersData() {
      return [
        { orderNo: '暂无订单', totalAmount: 0, createTime: new Date() }
      ]
    },

    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')

      return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return this.formatDate(date)
      }
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 点击跳转方法
    handleOrderClick() {
      this.$router.push('/order/order')
    },

    handleProductClick() {
      this.$router.push('/good_shop/product')
    },

    handleUserClick() {
      this.$router.push('/system/user')
    },

    handleRefundClick() {
      this.$router.push('/evaluation/refund')
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

// 欢迎区域样式
.welcome-section {
  margin-bottom: 20px;

  .welcome-card {
    border-radius: 8px;

    .welcome-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .welcome-text {
        h2 {
          margin: 0 0 10px 0;
          color: #303133;
          font-size: 24px;
          font-weight: 600;
        }

        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }

      .welcome-icon {
        font-size: 48px;
        color: #409EFF;
      }
    }
  }
}

// 统计卡片样式
.stats-section {
  margin-bottom: 20px;

  .stats-card {
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
    }

    .stats-content {
      display: flex;
      align-items: center;

      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
        margin-right: 15px;

        &.orders {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.products {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.users {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.revenue {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }

        &.refunds {
          background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
        }
      }

      .stats-info {
        flex: 1;

        .stats-number {
          font-size: 28px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 5px;
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }

    .stats-footer {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #f0f0f0;

      .stats-trend {
        font-size: 12px;

        &.up {
          color: #67C23A;
        }

        &.down {
          color: #F56C6C;
        }
      }
    }
  }
}

// 图表区域样式
.charts-section {
  margin-bottom: 20px;

  .chart-card {
    border-radius: 8px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .chart-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .hot-products-list {
    .hot-product-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .product-rank {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: #409EFF;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: 600;
        margin-right: 15px;
      }

      .product-info {
        flex: 1;

        .product-name {
          font-size: 14px;
          color: #303133;
          margin-bottom: 5px;
        }

        .product-sales {
          font-size: 12px;
          color: #909399;
        }
      }

      .product-amount {
        font-size: 16px;
        font-weight: 600;
        color: #E6A23C;
      }
    }
  }
}

// 最近动态样式
.recent-section {
  .recent-card {
    border-radius: 8px;

    .recent-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .recent-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .recent-list {
    .recent-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .item-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #409EFF;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
      }

      .item-content {
        flex: 1;

        .item-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 5px;
        }

        .item-desc {
          font-size: 12px;
          color: #909399;
        }
      }

      .item-time {
        font-size: 12px;
        color: #C0C4CC;
      }
    }
  }

  .system-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        font-size: 14px;
        color: #606266;
      }

      .info-value {
        font-size: 14px;
        color: #303133;
        font-weight: 500;
      }
    }
  }
}

// 无数据样式
.no-data {
  text-align: center;
  padding: 40px 0;
  color: #C0C4CC;

  i {
    font-size: 48px;
    margin-bottom: 10px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .welcome-content {
    flex-direction: column;
    text-align: center;

    .welcome-icon {
      margin-top: 20px;
    }
  }

  .stats-content {
    .stats-icon {
      width: 50px;
      height: 50px;
      font-size: 20px;
    }

    .stats-info .stats-number {
      font-size: 24px;
    }
  }

  .chart-header {
    flex-direction: column;
    align-items: flex-start;

    .chart-controls {
      margin-top: 10px;
    }
  }
}
</style>

